import {deepFullCopy, messages, paramsParse} from "share/common";
import React from 'react'
import { connect } from 'react-redux'
import {Button, Table, Badge, Popover, Menu, Dropdown, Icon,} from 'antd';
import SearchArea from 'components/search-area';
import config from 'config'
import SlideFrame from 'components/slide-frame'
import ListSelector from 'components/list-selector'
import 'styles/financial-management/supplier-management/supplier-management.scss'
import menuRoute from 'routes/menuRoute'
import moment from 'moment'
import ResizeTable from 'components/resize-table'
import CustomerInfoMaintenanceService from 'containers/customer-info-maintenance/customer-info-maintenance.service'
import NewCustomerInfo from 'containers/customer-info-maintenance/new-customer-info'
import ImportModal from "components/template/import-modal-ie/import-modal";
import ExportModal from "components/template/export-modal/export-modal";

class CustomerInfoMaintenance extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      tenant: window.location.href.indexOf('tenant') !== -1,
      type: window.location.href.indexOf('tenant') !== -1 ? 'tenant' : 'company',
      loading: false,
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        disuse: 0,
        pageSize: 10,
      },
      searchParams:{
        type: "",
        code: "",
        name: "",
        bankAccount: "",
        isEnabled: null,
      },
      searchForm: [
        {
          type: 'select', id: 'type', label: messages('customer-info-maintenance.key1')/*客户类型*/, valueKey: 'id', labelKey: 'customerTypeName', options: [],
          getUrl: `${config.baseUrl}/api/customer/type/list?enabled=true`, method: 'get', getParams: { page: 0, size: 99999 }
        },
        { type: 'input', id: 'code', label: messages('customer-info-maintenance.key2')/*客户代码*/, },
        { type: 'input', id: 'name', label: messages('customer-info-maintenance.key3')/*客户名称*/, },
        { type: 'input', id: 'bankAccount', label: messages('financial-management.key319'/*银行账号*/), },
        {
          type: 'radio', id: 'isEnabled', label: messages('common.column.status')/*状态*/,
          options: [
            { label: messages('financial-management.key367'/*全部*/), value: null },
            { label: messages('common.status.enable'), value: true },
            { label: messages('common.status.disable'), value: false },
          ],
          defaultValue: null
        },
      ],
      columns: [
        {
          title: messages('customer-info-maintenance.key2')/*客户代码*/, key: "customerCode", dataIndex: 'customerCode',
          render: text => <span>{text ? <Popover content={text}>{text}</Popover> : '-'}</span>
        },
        {
          title: messages('customer-info-maintenance.key3')/*客户名称*/, key: "customerName", dataIndex: 'customerName',
          render: text =>
            <span>
              <Popover content={text} placement="topLeft" overlayStyle={{maxWidth: 800}}>
                {text ? text : "-"}
              </Popover>
            </span>
        },
        {
          title: messages('customer-info-maintenance.key1')/*客户类型*/, key: "customerTypeName", dataIndex: 'customerTypeName',
          render: value => <span><Popover content={value}>{value ? value : "-"}</Popover></span>
        },
        {
          title: messages('financial-management.key370'/*最近更新时间*/), key: "lastModifiedDate", dataIndex: 'lastModifiedDate',
          render: value => value ? moment(new Date(value)).format("YYYY-MM-DD") : null
        },
        {
          title: messages('common.column.status'), key: 'status', dataIndex: 'enabled', width: '7%',
          render: value => (
            <Badge status={value ? 'success' : 'error'}
                   text={value ? messages("common.status.enable") : messages("common.status.disable")} />)
        },
        {
          title: messages('common.operation'), key: 'operation', width: '20%',
          render: (text, record, index) => (this.renderOperation(text, record, index))
        },
      ],
      innerColumns: [
        {
          title: messages('financial-management.key347'/*序号*/), key: "order", dataIndex: 'order',
          render: (text, record, index) => <span>{index + 1}</span>
        },
        {
          title: messages('financial-management.key319'/*银行账号*/), key: "bankAccount", dataIndex: 'bankAccount'
        },
        {
          title: messages('financial-management.key298'/*银行代码*/), key: "bankCode", dataIndex: 'bankCode'
        },
        {
          title: messages('financial-management.key368'/*银行名称*/), key: "bankName", dataIndex: 'bankName'
        },
        {
          title: messages('financial-management.key369'/*国家*/), key: "country", dataIndex: 'country',
          render: text => <span>{text ? text : "-"}</span>
        },
        {
          title: messages('financial-management.key300'/*开户地*/), key: "bankAddress", dataIndex: 'bankAddress',
          render: text => <span>{text ? <Popover content={text}>{text}</Popover> : "-"}</span>
        },
        {
          title: messages('financial-management.key370'/*最近更新时间*/), key: "lastModifiedDate", dataIndex: 'lastModifiedDate',
          render: value => value ? moment(new Date(value)).format("YYYY-MM-DD") : null
        },
        {
          title: messages('common.column.status'), key: 'enabled', dataIndex: 'enabled', width: '8%',
          render: value => (
            <Badge status={value ? 'success' : 'error'}
                   text={value ? messages("common.status.enable") : messages("common.status.disable")} />)
        },
      ],
      showImportFrame: false,
      selectedEntityOIDs: [],  //已选择的列表项的OIDs
      record: null,
      visible: false,
      customerList: [],
      id: null,
      selectedRowKeys: [],
      companyListSelector: false,
      searchKey: 0,
    }
  }

  componentWillMount() {
    this.initData();
  }

  componentWillReceiveProps(nextProps){
    if(this.props.location.pathname !== nextProps.location.pathname){
      let tenant = nextProps.location.pathname.indexOf('tenant') !== -1;
      let type = tenant ? 'tenant' : 'company';
      this.setState({
        tenant,
        type,
        visible: false,
        id: null,
        searchParams:{
          type:"",
          code:"",
          name:"",
          bankAccount:"",
          isEnabled:"",
        },
        pagination: {
          current: 1,
          page: 0,
          total: 0,
          disuse: 0,
          pageSize: 10,
        },
        searchKey: this.state.searchKey + 1,
      }, () => {
        this.initData();
      });
    }
  }

  initData = () => {
    let _pagination = this.getBeforePage();
    let pagination = this.state.pagination;
    pagination.page = _pagination.page;
    pagination.current = _pagination.page + 1;
    this.setState({
      pagination,
    }, () => {
      this.getList();
    });
  };

  renderOperation = (text, record, index) => {
    return (
      <span>
              {/*如果是 TENANT且公司模式公司模式  就不能编辑*/}
        {!(!this.state.tenant && record.source === "TENANT") && this.checkNewAuth() ?
            <a href="#" onClick={(e) => this.editItem(e, record, index)}>{messages("common.edit")}</a>
            : messages("common.edit")}
            <span className="ant-divider"/>
            <a onClick={(e) => this.handleLinkAccount(e, record, index)}>
              {messages('financial-management.key319'/*银行账号*/)}
            </a>
            {this.state.tenant && <span className="ant-divider"/>}
            {
              this.state.tenant &&
              <a href="#" onClick={(e) => this.handleLinkCompany(e, record, index)}>
                {messages('financial-management.key372'/*分配公司*/)}
              </a>
            }
      </span>
    )
  };

  handleLinkAccount = (e, record, index) => {
    e.stopPropagation();
    const {type} = this.state;
    this.setBeforePage(this.state.pagination);
    let pathComp = menuRoute.getRouteItem(`customer-bank-account-${type}`, 'key');
    //source是判定此供应商属于公司还是租户，
    //公司模式下，租户级供应商不能编辑
    let path = pathComp.url.replace(':id', record.id).replace(":source", record.source);
    this.context.router.push(path);
  };

  handleLinkCompany = (e, record, index) => {
    e.stopPropagation();
    const {type} = this.state;
    this.setBeforePage(this.state.pagination);
    let pathComp = menuRoute.getRouteItem(`customer-assign-company-${type}`, 'key');
    let path = pathComp.url.replace(':id', record.id);
    this.context.router.push(path);
  };

  handleSearch = (params) => {
    let { pagination } = this.state;
    pagination.page = 0;
    this.setState({
      pagination,
      searchParams: params
    }, () => {
      this.getList();
    });
  };

  //分页点击
  onChangePager = (pagination) => {
    let temp = this.state.pagination;
    temp.page = pagination.current - 1;
    temp.current = pagination.current;
    temp.pageSize = pagination.pageSize;
    this.setState({
      loading: true,
      pagination: temp
    }, () => {
      this.getList();
    })
  };


  getList = () => {
    this.setState({ loading: true });
    let { pagination, tenant, searchParams, customerList } = this.state;
    let params = Object.assign({page: pagination.page, size: 10}, searchParams);
    params.source = tenant ? "TENANT" : "COMPANY";
    CustomerInfoMaintenanceService.getCustomerList(params).then((response) => {
      let pagination = this.state.pagination;
      pagination.total = Number(response.headers['x-total-count']) || 0;
      customerList = [];
      response.data.map(item => {
        let param = {
          customerTypeName: item.customerType.customerTypeName,
          customerBankInfoList: item.customerBankInfoList,
        };
        customerList.push(Object.assign(item.customer, param));
      });
      this.setState({
        customerList,
        loading: false,
        pagination,
      })
    }).catch(err => {
      this.setState({
        loading: false,
      })
    });
  };

  //新建侧滑
  handleCreate = () => {
    this.setState({
      visible: true,
      id: null,
    })
  };

  editItem = (e, record) => {
    e.stopPropagation();
    if (record.effectiveDate) {
      record.effectiveDate = moment(new Date(record.effectiveDate));
    } else {
      record.effectiveDate = null;
    }
    this.setState({
      id: record.id,
      visible: true,
    })
  };

  afterClose = () => {
    this.setState({
      id: null,
      visible: false,
    });
    this.getList();
  };

  renderInnerTable = (record) => {
    const { innerColumns } = this.state;
    return (
      <Table
        columns={innerColumns}
        dataSource={record.customerBankInfoList || []}
        rowKey="id"
        pagination={false}/>
    )
  };
  //点击清除
  clearHandle = () => {
    this.setState({
      page: 0,
      pagination: {
        current: 1,
        page: 0,
        total: 0,
        disuse: 0,
        pageSize: 10,
      },
      searchParams: {
        type: "",
        code: "",
        name: "",
        bankAccount: "",
        isEnabled: ""
      },
    }, () => {
      this.getList();
    });
  };

  onSelectChange = (selectedRowKeys) => {
    this.setState({
      selectedRowKeys,
    })
  };

  showListSelector = (bool) => {
    this.setState({
      companyListSelector: bool,
    })
  };

  handleListOk = (result) => {
    const {selectedRowKeys} = this.state;
    if (result.result.length > 0) {
      let arr = [];
      result.result.map(item => {
        arr.push(item.id)
      });
      let params = {companyIdList: arr, customerIdList: selectedRowKeys};
      this.assignPartCompany(params);
    }
    this.showListSelector(false)
  };

  //分配部分公司
  assignPartCompany = (params) => {
    CustomerInfoMaintenanceService.assignPartCompany(params).then(res => {
      this.setState({
        selectedRowKeys: [],
      })
      }
    ).catch(err => {
    })
  };

  //渲染导出的列表
  renderExportList = (list) => {
    let {tenant, searchParams} = this.state;
    let exportCondition = Object.assign({source: tenant ? "tenant" : "company"}, deepFullCopy(searchParams));
    return list.map((data) => {
      return (
      <Menu.Item key={data.command}>
        <ExportModal
          codeCheck={true}
          exportTitle={data.title}
          exportType={data.command}
          exportCondition={{customerExportCommand: exportCondition}}
          exportCommand={data.command}
        />
      </Menu.Item>
      )
    })
  };

  renderExportMenu = () => {
    let {tenant} = this.state;
    let exportList = [
      {
        title: messages('customer-info-maintenance.key23')/*导出客户信息基本信息*/,
        command: "CUSTOMER_INFO",
      },
      {
        title: messages('customer-info-maintenance.key24')/*导出客户信息银行账号信息*/,
        command: "CUSTOMER_BANK",
      },
    ];
    if(tenant){
      exportList.push(
        {
          title: messages('customer-info-maintenance.key25')/*导出客户信息分配公司信息*/,
          command: "CUSTOMER_DISTRIBUTE_COMPANY",
        },
      );
    }
    const menu = (
      <Menu>{this.renderExportList(exportList)}</Menu>
    );
    return(
      <div className="drop-down-export-modal-wrap" style={{display: "inline-block"}}>
        <Dropdown overlay={menu}>
          <a className="ant-dropdown-link" href="#">
            {messages('customer-info-maintenance.key26')/*导出客户信息数据*/} &nbsp;<Icon type="down"/>
          </a>
        </Dropdown>
      </div>
    )
  };

  //非租户模式只显示新增按钮
  renderNewByTenant = () => {
    const { tenant, selectedRowKeys} = this.state;
    const templates = [
      {
        downloadName: messages('customer-info-maintenance.key27')/*客户信息导入模板下载*/,
        templateName: messages('customer-info-maintenance.key28')/*客户信息导入模板*/,
        downloadUrl: `/api/customer/template/export?type=CUSTOMER_INFO`,
        downloading: "supplierLoading"
      },
      {
        downloadName: messages('customer-info-maintenance.key29')/*客户信息银行导入模板下载*/,
        templateName: messages('customer-info-maintenance.key30')/*客户信息银行导入模板*/,
        downloadUrl: `/api/customer/template/export?type=CUSTOMER_BANK`,
        downloading: "supplierBankLoading"
      },
    ];
    if(tenant){
      templates.push(
        {
          downloadName: messages('customer-info-maintenance.key31')/*客户信息分配公司导入模板下载*/,
          templateName: messages('customer-info-maintenance.key32')/*客户信息分配公司导入模板*/,
          downloadUrl: "/api/customer/template/export?type=CUSTOMER_DISTRIBUTE_COMPANY",
          downloading: "supplierCompanyLoading"
        },
      )
    }
    return (
      <div className="table-header-buttons">
        {
          this.checkNewAuth() &&
          <Button type="primary" onClick={this.handleCreate}>{/*新建*/}{messages('common.create')}</Button>
        }
        {
          this.checkNewAuth() && tenant &&
          <Button onClick={() => this.showListSelector(true)} disabled={!selectedRowKeys.length}>
            {messages('financial-management.key372'/*分配公司*/)}
          </Button>
        }
        &nbsp;&nbsp;&nbsp;
        <ImportModal buttonName={messages('customer-info-maintenance.key33')/*客户信息导入*/}
                     templates={templates}
                     hasErrInfo={true}
                     uploadParams={""}
                     uploadUrl={`${config.baseUrl}/api/customer/import${tenant ? "?roleType=TENANT" : ""}`}
                     showErrUrl={`${config.baseUrl}` + "/api/customer/failed/logs?transactionOID=${transactionOID}"}
                     exportErrUrl={`${config.baseUrl}` + "/api/customer/failed/export?transactionOID=${transactionOID}"}
                     onCancel={this.initData}/>
        &nbsp;&nbsp;&nbsp;
        {this.renderExportMenu()}
      </div>
    )
  };

  render() {
    const { loading, searchForm, columns, pagination , visible, customerList, id, tenant, selectedRowKeys,
      companyListSelector, searchKey} = this.state;
    let rowSelection = {
      selectedRowKeys,
      onChange: this.onSelectChange,
    };
    return (
      <div className="supplier-management">
        <SearchArea key={searchKey}
          searchForm={searchForm}
          clearHandle={this.clearHandle}
          submitHandle={this.handleSearch} />
        <div className="table-header">
          <div className="table-header-title">
            {messages('senior-service-open.key32',{arg1:pagination.total})/*共搜索到 {arg1} 条数据*/}
            {
              selectedRowKeys.length ?
                <span style={{color: "#4e5b71"}}>&nbsp;/&nbsp;{messages('setting.key1447',{arg1:selectedRowKeys.length})/*已选择 {arg1} 条数据*/}</span>
                : null
            }
          </div>
          {this.renderNewByTenant()}
        </div>

        <ResizeTable
          className="components-table-demo-nested"
          loading={loading}
          dataSource={customerList}
          columns={columns}
          rowSelection={tenant ? rowSelection : null}
          expandedRowRender={this.renderInnerTable}
          pagination={pagination}
          onChange={this.onChangePager}
          size="middle"
          rowKey="id"
        />
        <SlideFrame
          isShowCloseBtn={false}
          title={id ? messages('customer-info-maintenance.key12')/*编辑客户信息*/ : messages('customer-info-maintenance.key13')/*新建客户信息*/}
          show={visible}
          content={NewCustomerInfo}
          afterClose={this.afterClose}
          params={{id: id, visible: visible}}/>
        <ListSelector type="vendor_company"
                      visible={companyListSelector}
                      onOk={this.handleListOk}
                      extraParams={{ tenantId: this.props.company.tenantId }}
                      onCancel={() => this.showListSelector(false)} />
      </div>)
  }
}

CustomerInfoMaintenance.contextTypes = {
  router: React.PropTypes.object
};

function mapStateToProps(state) {
  return {
    user: state.login.user,
    company: state.login.company,
    authToken: state.main.authToken,
  }
}

export default connect(mapStateToProps)(CustomerInfoMaintenance);
